package com.yuwei.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public Object getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public void setString(String key, Object obj) {
        set(key, obj, null);
    }

    public void setString(String key, Object obj, Long timeOut) {
        set(key, obj, timeOut);
    }

    public void set(String key, Object obj, Long timeOut) {
        if (obj == null) {
            System.out.println("obj的值为空！");
            return;
        }
        if (obj instanceof String) {
            String val = (String) obj;
            stringRedisTemplate.opsForValue().set(key, val);
            System.out.println("设置值");
            if (timeOut != null)
                stringRedisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
        }
    }
}
